package com.example.baselibrary.db;

import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.example.baselibrary.bean.UserManager;
import com.example.baselibrary.db.table.AccountTable;
import com.example.baselibrary.db.table.AttentionTable;
import com.example.baselibrary.db.table.DNDTable;
import com.example.baselibrary.db.table.FileDownLoadTable;
import com.example.baselibrary.db.table.FileSearchHistoryTable;
import com.example.baselibrary.db.table.GroupMemberTable;
import com.example.baselibrary.db.table.GroupTable;
import com.example.baselibrary.db.table.IMTopTable;
import com.example.baselibrary.db.table.SearchHistoryTable;
import com.example.baselibrary.db.table.TopContactsTable;
import com.j256.ormlite.support.ConnectionSource;

import java.util.Locale;

import cc.vv.lklibrary.db.help.DBBaseOpenHelper;
import cc.vv.lklibrary.db.operate.DBTableOperate;

/**
 * 数据库配置
 *
 * @author: NPF
 * @date: 2018/3/13.
 */
public class BTDBHelper extends DBBaseOpenHelper {
    /**
     * 数据库名称
     */
    private static String DBNAME = "bt_";
    /**
     * 数据库版本
     */
    private static final int DBVERSION = 2;

    public BTDBHelper(String dbName, int dbVersion, Class... tableBeanClass) {
        super(dbName, dbVersion, tableBeanClass);
    }

    private static BTDBHelper mInstance;

    /**
     * 配置表映射实体
     */
    public static BTDBHelper getInstance() {
        String mineAccount = UserManager.Companion.getUserId();
        if (!TextUtils.isEmpty(mineAccount)) {
            mineAccount = mineAccount.replace("-", "");
        }
        String currentDBName = String.format(Locale.CHINESE, "bt_%s", mineAccount);
        if (!currentDBName.equals(DBNAME)) {
            mInstance = null;
        }
        if (null == mInstance) {
            synchronized (BTDBHelper.class) {
                if (null == mInstance) {
                    mInstance = new BTDBHelper(DBNAME, DBVERSION, AccountTable.class, GroupTable.class,
                            GroupMemberTable.class, DNDTable.class, IMTopTable.class, AttentionTable.class,
                            TopContactsTable.class, FileSearchHistoryTable.class, FileDownLoadTable.class,
                            SearchHistoryTable.class);
                }
            }
        }
        return mInstance;
    }

    /**
     * 数据库更新
     *
     * @param sqLiteDatabase
     * @param connectionSource
     * @param i
     * @param i1
     */
    @Override
    protected void update(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        // 清空原常用联系人表数据
        sqLiteDatabase.execSQL("delete from topContacts");
        // 更新表, 添加 mobile 字段
        DBTableOperate.getInstance().columnAdd(sqLiteDatabase, "topContacts", "mobile", "varchar", "10086");
    }
}